package com.smart.service.impl;

import java.util.Date;
import com.smart.dao.CaptchaDao;
import javax.annotation.Resource;
import com.smart.entity.SysCaptcha;
import cn.hutool.core.date.DateUtil;
import java.awt.image.BufferedImage;
import com.google.code.kaptcha.Producer;
import com.smart.service.CaptchaService;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;

/**
 * @author lgb
 * @date 2020年6月8日 下午7:47:04
 * Copyright (C) 深圳工勘科技
 * @说明: 图片验证码
 **/
@Service("captchaService")
public class CaptchaServiceImpl extends ServiceImpl<CaptchaDao,
			SysCaptcha> implements CaptchaService{

	@Resource
	private Producer producer;
	
	@Override
	public BufferedImage getCaptcha(String uuid){
		if (StringUtils.isBlank(uuid)) {
            throw new RuntimeException("uuid为空");
        }
        //生成文字验证码
        String code = producer.createText();
        SysCaptcha captchaEntity = new SysCaptcha();
        captchaEntity.setUuid(uuid);
        captchaEntity.setCode(code);
        //5分钟后过期
        captchaEntity.setExpireTime(DateUtil.offsetMinute(new Date(), 5));
        save(captchaEntity);
		return producer.createImage(code);
	}

	@Override
	public boolean validate(String uuid,String code) {
        SysCaptcha captchaEntity = this.baseMapper.selectOne(new LambdaQueryWrapper<SysCaptcha>()
                .eq(SysCaptcha::getUuid, uuid));
        if (captchaEntity == null) {
            return false;
        }
        //删除验证码
        removeById(uuid);
        if (captchaEntity.getCode().equalsIgnoreCase(code) && 
        		captchaEntity.getExpireTime().getTime() >= 
        			System.currentTimeMillis()) {
            return true;
        }
        return false;
    }

}